package com.whzykj.ctrl;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLDecoder;

import com.jfinal.core.Controller;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.whzykj.common.CommonUtils;
import com.whzykj.common.ServiceConstants;
import com.whzykj.common.JsonUtil;
import com.whzykj.common.ReturnEnum;
/**
 * http://localhost:8888/lezui/mobile/interface.do?content={type:'userinfo',loginid:'8001'}
 * @author lenovo 
 *
 */
public class AppInterfaceController extends Controller {
	private static Logger log = Logger.getLogger(AppInterfaceController.class);
	public void Interface() {
		try {
			long a = System.currentTimeMillis();
			// 返回的结果对象
			JSONObject result = new JSONObject();
			// 获取参数
			String content = getPara("content");
			log.info("request------->" + content);
			JSONObject messageObj = JSONObject.fromObject(URLDecoder.decode(content.replaceAll("%", "%25"), "utf-8"));
			String type = (String) messageObj.getString("type");
			Object nspace = messageObj.get("namespace");
			if(nspace == null){
				 nspace = messageObj.get("nspace");
			}     
			String namespace = "";
			if(nspace == null || StringUtils.isEmpty(nspace.toString())){
				JsonUtil.put(result, ReturnEnum.NAMESPACE_ERROR);
			}else if(StringUtils.isEmpty(type)){
				JsonUtil.put(result, ReturnEnum.TYPE_ERROR);
			}else{
				namespace = nspace.toString();
				result.put("type", type);
				Class<?> clz=null;
				try {
					messageObj.put("ip", CommonUtils.getIpAddr(getRequest()));
					String className = ServiceConstants.getNameSpace(namespace);
					clz = Class.forName("com.whzykj.resource."+className);
					Method thd = clz.getMethod(type, messageObj.getClass(),result.getClass());
					thd.invoke(enhance(clz),new Object[] { messageObj, result });
				} catch (Exception e) {
					log.error(e.getMessage(),e);
					e.printStackTrace();
					JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
				}
			}
			JSONObject o =  new JSONObject();
			o.put("type", type);
			//成功码做下调整   成功都返回S0000
			if(result.get("code") != null && result.get("code").toString().startsWith("S0")){
				o.put("code", ReturnEnum.RETURN_SUCCESS.getCode());
			}else{
				o.put("code",  result.get("code"));
			}
			o.put("msg", result.get("errormsg"));
			result.remove("code");
			result.remove("type");
			result.remove("errormsg");
			if(result.get("data") == null){
				o.put("data", result.toString());
			}else{
				o.put("data", result.get("data"));
			}
			this.renderJson(o.toString());
			log.info(o.toString());
			log.info("----------[" + type + "] execute time  ---->"+ (System.currentTimeMillis() - a) / 1000f + "s");
		} catch (IOException e) {
			this.renderJson(e.getMessage());
			e.printStackTrace();
		}
	}
}
